package nio.nio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zengjian
 * @create 2018-05-27 10:16
 * @since 1.0.0
 */
public class NIO2Client implements Runnable {

    public static void main(String[] args) throws IOException {
        new Thread(new NIO2Client()).start();
    }

    private static String hostname = "127.0.0.1";
    private static int port = 8080;
    private SocketChannel socketChannel;
    private Selector selector;
    private volatile boolean stoped;

    public NIO2Client() {
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            System.out.println("client start");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            doConnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (!stoped) {
            try {
                selector.select(1000);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isValid()) {
                    if (key.isConnectable()) {
                        try {
                            doConnect();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (key.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        int read = 0;
                        try {
                            read = socketChannel.read(byteBuffer);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        if (read > 0) {
                            byteBuffer.flip();
                            byte[] bytes = new byte[byteBuffer.remaining()];
                            byteBuffer.get(bytes);
                            try {
                                System.out.println(new String(bytes, "utf-8"));
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        } else if (read == 0) {

                        } else {

                        }
                    }

                }
            }


        }
    }

//    private void doConnect() {
//        try {
//            if (socketChannel.connect(new InetSocketAddress(hostname, port))){
//                socketChannel.register(selector, SelectionKey.OP_READ);
//                doWrite();
//                System.out.println("写请求");
//            }
//            else {
//                // TODO
//                System.out.println("没连接上");
//                socketChannel.register(selector, SelectionKey.OP_CONNECT);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    private void doConnect() throws IOException {
        // 如果连接成功，则注册到多路复用器上，发送请求消息，读应答
        if (socketChannel.connect(new InetSocketAddress(hostname, port))) {
            socketChannel.register(selector, SelectionKey.OP_READ);
            doWrite(socketChannel);
        } else {
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
        }
    }

    private void doWrite(SocketChannel sc) throws IOException {
        byte[] req = "QUERY TIME ORDER".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        sc.write(writeBuffer);
        if (!writeBuffer.hasRemaining()) {
            System.out.println("send order success...");
        }
    }

    private void doWrite() throws IOException {
        String req = "req";
        byte[] bytes = req.getBytes();
        ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
        byteBuffer.put(bytes);
        byteBuffer.flip();
        socketChannel.write(byteBuffer);
    }
}
